# 构建用户画像
from sklearn.feature_extraction.text import TfidfVectorizer
import csv
import io
import json
import sys
import jieba

from flask import jsonify
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from py2neo import Graph
import pandas as pd
import mysql.connector

from bulid_distance import city_similarity, read_cities_data, get_ex_cities

sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


class UserProfile:
    def __init__(self, job_id):
        self.job_id = job_id


# def recommend_positions(user_profile, knowledge_graph):


if __name__ == '__main__':
    # 获取通过命令行传递的参数
    description = sys.argv[1]
    # description = "岗位职责：1.负责web前端开发；2.优化前端代码和性能，保持良好的兼容性；3.学习前端前沿技术，完善用户体验；职位要求：1.1-3年WEB前端开发经验；2.精通JavaScript、HTML、CSS、等WEB前端技术；3.熟练使用GIT，掌握React、Vue.js、AngularJS框架至少一种；4. 精通JSON、restful 等通信格式以及基于AJAX请求实现与后台数据交互；5.有良好的编码习惯；6.熟练使用一种或多种前端主流开发框架, Ant Design。7.较强的工作责任心、沟通表达与良好的执行力，富有工作热情和团队意识，抗压能力强。"

    # 建立数据库连接
    cnx = mysql.connector.connect(user='root', password='xiyou666',
                                  host='8.219.11.92', database='recommend')

    # 创建游标对象
    cursor = cnx.cursor()
    user_result = []
    results = []
    # 执行查询语句
    # 定义查询语句
    query = "SELECT * FROM resume"

    # 执行查询
    cursor.execute(query)

    # 获取查询结果
    result_category = cursor.fetchall()

    if result_category:
        for result in result_category:
            username = result[0]
            realname = result[1]
            age = result[2]
            education = result[3]
            school = result[4]
            phone = result[5]
            city = result[6]
            salary = result[7]
            if result[9]:
                skills = result[9]
            else:
                skills = []  # 设置一个默认空列表
            file = result[10]

            # 对岗位描述和简历进行分词
            job_description_words = " ".join(jieba.cut(description))
            resume_words = " ".join(jieba.cut(skills))
            # 使用 TF-IDF 向量化文本
            vectorizer = TfidfVectorizer()
            job_resume_matrix = vectorizer.fit_transform([job_description_words, resume_words])

            # 获取向量化后的文本表示
            job_vector = job_resume_matrix[0]
            resume_vector = job_resume_matrix[1]

            # 计算岗位描述和简历之间的余弦相似度
            similarity_score = cosine_similarity(job_vector, resume_vector)

            if similarity_score > 0.01:
            # 将结果添加到列表中
                results.append(
                    {"similarity": similarity_score, "username": username, "realname": realname, "age": age,
                     "education": education, "school": school, "phone": phone, "city": city, "salary": salary,
                     "skills": skills, "file": file})

        # 按照相似度从大到小进行排序
        results.sort(key=lambda x: x["similarity"], reverse=True)
        print(results)
        # 打印结果
        result_dict = []
        for result1 in results:
            user_dict = {
                "similarity": result1["similarity"][0][0],
                "username": result1["username"],
                "realname": result1["realname"],
                "age": result1["age"],
                "education": result1["education"],
                "school": result1["school"],
                "phone": result1["phone"],
                "city": result1["city"],
                "salary": result1["salary"],
                "file": result1["file"],
            }
            result_dict.append(user_dict)
        json_result = json.dumps(result_dict, ensure_ascii=False)
        print(json_result)
    # 关闭游标和数据库连接
    cursor.close()
    cnx.close()
